<?php


namespace App\Http\Controllers\Agent;


use App\Contract\Platform;
use App\Http\Resources\PaginationCollection;
use App\Http\Service\DeviceService;
use App\Jobs\DeviceQuery;
use App\Model\Business;
use App\Model\DeviceBus;
use App\Model\DeviceLog;
use App\Model\House;
use App\Model\Order;
use App\Model\TtlockData;
use App\User;
use Carbon\Carbon;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Controller;
use App\Model\Agent;
use App\Model\Device;
use App\Model\TestRecord;
use App\Tools\Helper;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class DeviceController extends Controller
{

    public function getBusiness(Request $request){
        $agent = Token::getUser();
        $business = Business::query()->where('agent_id',$agent->id)
            ->with('user')
            ->get();
        return Result::success($business);

    }

    public function detail(Request $request){
        $deviceId = $request->input('device_id');
        $device = Device::query()->where('id',$deviceId)->with('house')->first();
        return Result::success($device);
    }



    # 充值
    public function recharge(Request $request)
    {
        $isRecharged = $request->input('isRecharged') ?? 0;
        $isPaid = $request->input('isPaid') ?? 0;
        $deviceModel = Device::where('mac', trim($request->input('mac')))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        if($deviceModel->recharge_disabled == 1){
            return Result::error(404, '设备充值被限制');
        }
//        if($deviceModel->signal == 0){
//            return Result::error(1001, '当前设备暂无信号');
//        }
        if ($request->input('du') > 10000) {
            return Result::error(404, '单次充值电量不可超过1万');
        }
        $deviceModel = Device::query()->where('mac', trim($request->input('mac')))->first();
        if ($deviceModel->du >= 100000) {
            return Result::error(404, '当前剩余电量已超过10万无需充值');
        }
        // todo 验证支付单
        $service = app()->make(DeviceService::class);
        $result = $service->rechargeAgent(trim($request->input('mac')), $request->input('du'), $request->input('amount'), $isRecharged, $isPaid);
        for($i=1;$i<4;$i++){
            dispatch(new DeviceQuery(trim($request->input('mac'))))->delay(6*$i);
        }
        return Result::success();
    }


    // 设备日志
    public function log(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $action = $request->input('action');
        $deviceId = $request->input('device_id');
        $time = $request->input('time');
        $query = DeviceLog::query();
        $data = $query->orderByDesc('id')
            ->where(function ($q) use ($action,$time,$deviceId) {
                if ($action) {
                    $q->where('action', $action);
                }
                if($time){
                    $q->where('created_at','>=',$time[0]);
                    $q->where('created_at','<=',$time[1]);
                }
                if($deviceId){
                    $q->where('device_id',$deviceId);
                }
            })
            ->paginate($limit, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }


    public function deviceList(Request $request){
        $page['page'] = $request->input('page',1);
        $page['limit'] = $request->input('limit',10);
        $page['keyword'] = $request->input('keyword');
        $page['agent_id'] = $request->input('agent_id');
        $page['business_id'] = $request->input('business_id');
        $page['online_status'] = $request->input('online_status');
        $agent = Token::getUser();
        if(!$agent){
            return Result::error(1001,'请先登录经销商');
        }
        $data['list'] = Device::query()->with('house')->where(function ($query) use ($page,$agent) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('sn', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['online_status'] > 0){
                $query->where('online_status',$page['online_status']);
                $query->where('house_id','>',0);
            }
            if($page['business_id']){
                $query->where('business_id',$page['business_id']);
            }
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
        })->orderBy('id','desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get();
        foreach($data['list'] as &$v){
            if($agent->pid > 0){
                $v['disabled'] = true;
            }else{
                if($v['agent_id'] != $agent->id || $v['business_id'] > 0){
                    $v['disabled'] = true;
                }else{
                    $v['disabled'] = false;
                }
            }
            if($v['business_id']){
                $business = Business::query()->where('id',$v['business_id'])->first();
                $v['business_name'] = $business->name;
                if($business->name){
                    $v['business_name'] = $business->name;
                }else{
                    $v['business_name'] = '未实名';
                }
                $v['business_mobile'] = User::query()->where('id',$business->user_id)
                    ->value('mobile');
            }else{
                $v['business_name'] = '';
                $v['business_mobile'] = '';
            }
        }
        $data['total'] = Device::query()->where(function ($query) use ($page,$agent) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('sn', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['online_status'] > 0){
                $query->where('online_status',$page['online_status']);
                $query->where('house_id','>',0);
            }
            if($page['business_id']){
                $query->where('business_id',$page['business_id']);
            }
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
        })->count();
        return Result::success($data);
    }


    public function deviceCount(Request $request){
        $agent = Token::getUser();
        if(!$agent){
            return Result::error(1001,'请先登录经销商');
        }

        $start = $request->input('start');
        $end = $request->input('end');
        $page['agent_id'] = $request->input('agent_id');
        $data['total'] = Device::query()->where(function ($query) use ($page,$agent) {
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
        })->count();
        $data['4g_total'] = Device::query()->where(function ($query) use ($page,$agent) {
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
            $query->where('is_master',1);
        })->count();

        $data['ble_total'] = Device::query()->where(function ($query) use ($page,$agent) {
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
            $query->where('is_master',0);
        })->count();

        $data['house_total'] = Device::query()->where(function ($query) use ($page,$agent,$start,$end) {
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
            if($start){
                $query->where('bind_at','>=',$start.' 00:00:00');
            }
            if($end){
                $query->where('bind_at','<=',$end.' 23:59:59');
            }
            $query->where('is_master',1);
            $query->where('house_id','>',0);
        })->count();
        $data['house_total_ble'] = Device::query()->where(function ($query) use ($page,$agent,$start,$end) {
            if($agent->pid){
                $query->where('agent_id',$agent->id);
            }else{
                if($page['agent_id']){
                    $query->where('agent_id',$page['agent_id']);
                }else{
                    $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                    $agentIds[] = $agent->id;
                    $query->whereIn('agent_id',$agentIds);
                }
            }
            if($start){
                $query->where('bind_at','>=',$start.' 00:00:00');
            }
            if($end){
                $query->where('bind_at','<=',$end.' 23:59:59');
            }
            $query->where('is_master',0);
            $query->where('house_id','>',0);
        })->count();

        return Result::success($data);
    }

    /**订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderList(Request $request){
        $agent = Token::getUser();
        if(!$agent){
            return Result::error(1001,'请先登录经销商');
        }
        $page['page'] = $request->input('page',1);
        $page['limit'] = $request->input('limit',10);
        $page['start'] = $request->input('start');
        $page['end'] = $request->input('end');
        $page['device_id'] = $request->input('device_id');
        $page['status'] = $request->input('status');
        $data['list'] = Order::query()->where(function ($query) use ($page,$agent) {
            if($page['start']){
                $query->where('created_at','>=',$page['start'].' 00:00:00');
            }
            if($page['end']){
                $query->where('created_at','<=',$page['end'].' 23:59:59');
            }
            $query->where('status',3);
            $query->where('is_draw',0);
            $query->where('recharge_status',3);
            if($page['device_id'] > 0){
                $query->where('device_id',$page['device_id']);
            }else{
                $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                $agentIds[] = $agent->id;
                $devices = Device::query()->whereIn('agent_id',$agentIds)->pluck('id')->toArray();
                $query->whereIn('device_id',$devices);
            }
        })->orderBy('id','desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get();
        $data['total'] = Order::query()->where(function ($query) use ($page,$agent) {
            if($page['start']){
                $query->where('created_at','>=',$page['start'].' 00:00:00');
            }
            if($page['end']){
                $query->where('created_at','<=',$page['end'].' 23:59:59');
            }
//            if($page['status']){
//                $query->where('status',3);
//            }
            $query->where('is_draw',0);
            $query->where('status',3);
            $query->where('recharge_status',3);
            if($page['device_id'] > 0){
                $query->where('device_id',$page['device_id']);
            }else{
                $agentIds = Agent::query()->where('pid', $agent->id)->pluck('id')->toArray();
                $agentIds[] = $agent->id;
                $devices = Device::query()->whereIn('agent_id',$agentIds)->pluck('id')->toArray();
                $query->whereIn('device_id',$devices);
            }
        })->count();
        return Result::success($data);
    }


    /**解绑设备
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbind(Request $request){
        $sn =  $request->input('sn');
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }

        $device  = Device::query()->where('sn',$sn)->first();
        if(!$device){
            return Result::error(500, '设备不存在2');
        }
        if($device->business_id){
            return Result::error(500, '设备已绑定设备不可回收');
        }
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }
        if($agentInfo->pid > 0){
            return Result::error(500, '您暂无权限回收设备');
        }
        if($device->agent_id != $agentInfo->id){
            return Result::error(500, '您暂无权限回收该设备');
        }
        $device->agent_id = $agentInfo->id;
        $device->deleted_at = date('Y-m-d H:i:s',time());
        $device->save();
        TestRecord::query()->where('sn',$device->sn)->delete();
        return Result::success();
    }

    /**检查是否有权限划拨设备
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkAgent(Request $request){
        $sn = $request->input('sn');
        if(!$sn){
            return Result::error(500, '请输入设备编号');
        }
        $agentInfo = Token::getUser();

        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }
        if($agentInfo->pid > 0){
            return Result::error(500, '您暂无权限划拨该设备');
        }
        $device = Device::query()->where('sn',$sn)->first();
        if(!$device){
            return Result::error(500, '设备编号不存在 请先完成产测');
        }
        if($device->agent_id != $agentInfo->id){
            return Result::error(500, '您暂无权限划拨该设备');
        }
        return Result::success();
    }

    /**批量划拨
     * @param Request $request
     * @return void
     */
    public function batchAgent(Request $request){
        $sns =  $request->input('sns');
        $agentId = $request->input('agentId');
        if(!$agentId){
            return Result::error(500, '请选择经销商');
        }
        $agentInfo = Token::getUser();
        DB::beginTransaction();
        foreach($sns as &$v)
        {
             $v = trim($v);
             $deviceModel = Device::query()->where('sn',$v)->first();
             if(!$deviceModel){
                 DB::rollBack();
                 return Result::error(500, '编号'.$v.'不存在,请修正后提交');
             }
            if($deviceModel->business_id){
                DB::rollBack();
                return Result::error(500, '编号'.$v.'已绑定房东，请修改后提交');
            }
            if($deviceModel->agent_id && $deviceModel->agent_id != $agentInfo->id){
                    DB::rollBack();
                    return Result::error(500, '编号'.$v.'不属于您，请删除后提交');
            }
             $deviceModel->agent_id = $agentId;
             $deviceModel->save();
        }
        DB::commit();
        return Result::success();
    }


    public function removeBusiness(Request $request){
        $sn = trim($request->input('sn'));
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }
        $device  = Device::query()->where('sn',$sn)->first();
        if(!$device){
            return Result::error(500,'设备号'. $sn.'不存在');
        }
        if($agentInfo->id != $device->agent_id){
            return Result::error(500, '只可解绑自己名下设备');
        }
        $device->business_id = null;
        $device->house_id = null;
        $device->bind_at = null;
        $device->save();
        return Result::success();
    }

    /**设备回收
     * @param Request $request
     * @return void
     */
    public function recoveryDevice(Request $request){
        $sn =  $request->input('sn');
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }

        $device  = Device::query()->where('sn',$sn)->first();
//        if($agentInfo->id != $device->agent_id){
//            return Result::error(500, '只可解绑自己名下设备');
//        }
        if(!$device){
            return Result::error(500, '设备不存在1');
        }
        if($device->business_id){
            return Result::error(500, '设备已绑定设备不可回收');
        }
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }
        if($agentInfo->pid > 0){
            return Result::error(500, '您暂无权限回收设备');
        }
        $device->agent_id = $agentInfo->id;
//        $device->deleted_at = date('Y-m-d H:i:s',time());
        $device->save();
//        TestRecord::query()->where('sn',$device->sn)->delete();
        return Result::success();
    }


    public function recoveryBatch(Request $request){
        $sn =  $request->input('sn');
        if(!$sn){
            return Result::error(500, '设备不存在');
        }
        if(!is_array($sn)){
            $sn = json_decode($sn,true);
        }
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }

        $devices  = Device::query()->whereIn('sn',$sn)->get();
        $agentInfo = Token::getUser();
        if(!$agentInfo){
            return Result::error(1001,'请先登录经销商');
        }
        if($agentInfo->pid > 0){
            return Result::error(500, '您暂无权限回收设备');
        }

        foreach($devices as $device){
            if($device->business_id){
                return Result::error(500, $device->sn.'设备已绑定设备不可回收');
            }
            $device->agent_id = $agentInfo->id;
            $device->save();
        }
        return Result::success();
    }



    public function read(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        $before = $deviceModel->du;
        $info = $request->input('info');
        $data = $request->all();
        if(isset($data['info'])){
            unset($data['info']);
        }
        $deviceModel->fill($data);
        $deviceModel->read_at = now()->toDateTimeString();
        $deviceModel->save();
//        $service = app()->make(DeviceService::class);
//        if($deviceModel->du == 0 && $deviceModel->online_status != 1 && $info == 'business'){
//            DeviceLog::create([
//                'action' => 1,
//                'device_id' => $deviceModel->id,
//                'log' => '电量手动清零',
//                'user_name' => $service->getUserName(),
//                'before'=>$before,
//                'after'=>0
//            ]);
//        }
        return Result::success($deviceModel);
    }


    public function deviceQrCode(Request $request, $id)
    {
        $device = Device::query()->find($id);

        if($device->qrcode && $device->qrcode != '[]') {
            return Result::success(['url' => $device->qrcode]);
        }

        $qrCode = new QrCode(env('APP_URL') . '/deviceDetail?sn=' . $device->sn);
        $qrCode->setSize(300);
        $qrCode->setMargin(10);

// Set advanced options
        $qrCode->setWriterByName('png');
        $qrCode->setEncoding('UTF-8');
        $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        //$qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER());
        //$qrCode->setLogoPath(__DIR__.'/../assets/images/symfony.png');
        //$qrCode->setLogoSize(150, 200);
        //$qrCode->setValidateResult(false);

// Round block sizes to improve readability and make the blocks sharper in pixel based outputs (like png).
// There are three approaches:
        $qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_MARGIN); // The size of the qr code is shrinked, if necessary, but the size of the final image remains unchanged due to additional margin being added (default)
        $qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_ENLARGE); // The size of the qr code and the final image is enlarged, if necessary
        $qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_SHRINK); // The size of the qr code and the final image is shrinked, if necessary

// Set additional writer options (SvgWriter example)
        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);

// Directly output the QR code
        //header('Content-Type: '.$qrCode->getContentType());
        //echo $qrCode->writeString();

// Save it to a file
        $qrCode->writeFile(public_path('/storage/qrcode/qrcode-' . $device->sn . '.png'));

// Generate a data URI to include image data inline (i.e. inside an <img> tag)
        //$dataUri = $qrCode->writeDataUri();

        $device->qrcode = env('APP_URL') . '/storage/qrcode/qrcode-' . $device->sn . '.png';
        $device->save();

        return Result::success(['url' => $device->qrcode]);
    }


    public function querySpeed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->querySpeed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }


    # 调表计量系数
    public function speed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }

        if($request->input('speed')>1200 && $deviceModel->type != 4){
            return Result::error(404, '公摊损耗不能超过120');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->speed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }


    public function update(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        //$deviceModel->fill($request->all());

        if ($request->input('house_id')) {
            $oldHouseId = $deviceModel->house_id;
            $deviceModel->house_id = $request->input('house_id');
            if ($oldHouseId) {
                $old = House::query()->where('id', $oldHouseId)->first();
                $new = House::query()->where('id', $deviceModel->house_id)->first();
                $str = $deviceModel->sn . '房源调整:' . $old->country . $old->name . '改为' . $new->country . $new->name;
            } else {
                $new = House::query()->where('id', $deviceModel->house_id)->first();
                $str = $deviceModel->sn . '房源调整:' . $new->country . $new->name;
            }
            $save['action'] = 11;
            $save['device_id'] = $deviceModel->id;
            $save['log'] = $str;
            $save['user_name'] = $this->getUser()->mobile;
            DeviceLog::create($save);
        }
        if ($request->input('low') != false) {
            $deviceModel->low = $request->input('low');
        }
        if ($request->input('price') != false) {
            if ($request->input('price') > 3) {
                return Result::error(401, '电量单价不可超过3元');
            }
            if ($request->input('price') < 0.1) {
                return Result::error(401, '电量单价不可小于0.1元');
            }
            $deviceModel->price = $request->input('price');
        }
        if($request->input('basic_price') != false){
            $deviceModel->basic_price = $request->input('basic_price');
        }
        if($request->input('service_price') != false){
            $deviceModel->service_price = $request->input('service_price');
        }
        if($request->input('bus_type') !== false){
            $deviceModel->bus_type = $request->input('bus_type');
        }
        if($request->input('business_show') !== false){
            $deviceModel->business_show = $request->input('business_show');
        }
        if($request->input('show_order') !== false){
            $deviceModel->show_order = $request->input('show_order');
        }
        $deviceModel->save();
        $deviceModel->load('house');
        return Result::success($deviceModel);
    }

    # 清0
    public function clear(Request $request)
    {
        $user = $this->getUser();
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->clear($request->input('mac'));
        $busInfo = DeviceBus::query()->where('device_id',$deviceModel->id)
            ->first();
        if($busInfo && $busInfo->clear){
            $busInfo->status = 0;
            $busInfo->save();
            $bus = DeviceBus::query()->where('id', $busInfo->pid)->first();
            if($bus && $bus->is_autoload){
                $count = DeviceBus::query()->where('type', 2)
                    ->where('status',1)
                    ->where('pid', $busInfo->pid)->count();
                $rate = number_format(100 /$count, 2);
                DeviceBus::query()->where('type', 2)
                    ->where('pid', $busInfo->pid)
                    ->where('status',1)
                    ->update(['rate' => $rate]);
            }
        }
        return Result::success();
    }

    public function restart(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->restart($request->input('mac'));
        return Result::success();
    }


    public function destroy($id)
    {
        $deviceModel = Device::where('id', $id)->first();
        if ($deviceModel) {
            if ($deviceModel->house_id) {
                $devices = Device::where('house_id', $deviceModel->house_id)
                    ->where('id', '<>', $id)
                    ->count();
                $locks = TtlockData::query()->where('house_id', $deviceModel->house_id)->count();
                if ($devices <= 0 && $locks <= 0) {
                    House::query()->where('id', $deviceModel->house_id)->delete();
                }
            }
            //$deviceModel->delete();
            $deviceModel->business_id = 0;
            $deviceModel->house_id = 0;
            $deviceModel->save();
            $checkBus = DeviceBus::query()->where('device_id', $deviceModel->id)->first();
            if($checkBus){
                DeviceBus::query()->where('pid',$checkBus->id)->delete();
                $checkBus->delete();
            }
        }
        return Result::success();
    }


    public function restartMaster(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $masterDevice = Device::where('mac',$deviceModel->m_mac)->first();
        if(!$masterDevice){
            return Result::error(404, '未找到主设备');
        }
        if($masterDevice->online_status != 1){
            return Result::error(404, '主设备不在线');
        }
        $key = 'cache_restart_'.$masterDevice->mac;
        if(Redis::exists($key)){
            return Result::error(404, '设备5分钟内请勿多次重启');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->restart($masterDevice->mac);
        Redis::setex($key,5*60,1);
        return Result::success();
    }


    public function batchDel(Request $request){
        $sns = $request->input('sns');
        if(!$sns){
            return Result::error(401,'请选择设备');
        }
        Device::query()->whereIn('sn',$sns)->delete();
        TestRecord::query()->whereIn('sn',$sns)->delete();
        return Result::success();
    }


}
